package tanhua.dubbo.server.service;

import com.tanhua.dubbo.server.pojo.TimeLine;
import com.tanhua.dubbo.server.pojo.Users;
import io.netty.util.concurrent.CompleteFuture;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @program: my-tanhua
 * @description:
 * @author: xuejingjing
 * @create: 2021-09-25 20:23
 **/

@Service
@Slf4j
public class TimeLineService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Async //异步执行，原理是：底层会开一个线程去执行该方法
    public CompletableFuture<String> saveTimeLine(Long userId, ObjectId publishId){
        //写入好友的时间线表

        //查询好友列表
        //根据userId用户id 在用户好友关系表中，查出来好友列表
        //查询条件
        try {
            Query query = Query.query(Criteria.where("userId").is(userId));
            //查询
            List<Users> usersList = mongoTemplate.find(query, Users.class);
            if(CollUtil.isEmpty(usersList)){
                //返回成功
                 return  CompletableFuture.completedFuture("ok");
            }
            //依次写入好友的时间线表中
            // 只要按字面意思填充就行，因为填充后自动会关联
            for(Users users : usersList){
                TimeLine  timeLine = new TimeLine();
                timeLine.setId(ObjectId.get());
                timeLine.setPublishId(publishId);
                timeLine.setUserId(userId);
                timeLine.setDate(System.currentTimeMillis());

                //写入数据,为啥是frendsid？因为是写入到好友的时间线表
                mongoTemplate.save(timeLine,"quanzi_time_line_"+ users.getFriendId());

            }
        } catch (Exception e) {
            log.error("写入好友时间线表失败~ userId"+ userId + e);
            //todo 事务回滚问题
            CompletableFuture.completedFuture("error");
        }

        return  CompletableFuture.completedFuture("ok");



    }